package tunnel;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.net.*;

/**
 * 小象代理隧道代理示例 - JAVA，类库 URL
 *
 * @author xxdl
 */
public class URLDemo {

    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String proxyHost = "http-dynamic-S02.xiaoxiangdaili.com";
    private static Integer proxyPort = 10030;

    private static String targetUrl = "https://httpbin.org/ip";

    public static void main(String[] args) throws Exception {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        Authenticator.setDefault(new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(appKey, appSecret.toCharArray());
            }
        });

        InputStream in = null;
        HttpURLConnection conn = null;
        for (int i = 0; i < 3; i++) {
            try {
                URL url = new URL(targetUrl);
                InetSocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
                java.net.Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                conn = (HttpURLConnection) url.openConnection(proxy);
                conn.connect();
                in = conn.getInputStream();
                System.out.println(IOUtils.toString(in));
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
                if (in != null) {
                    in.close();
                }
            }
        }
    }
}

